<?php

/*
* 案件导入
*/

class BashhandelController extends Controller_Base
{
    public function init()
    {
        parent::init();
    }


    //案件上传批次列表
    public function indexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $mediationOrganId  = intval($request->getQuery('mediationOrganId', 0));
        $submitStatus = intval($request->getQuery('submitStatus', 0));
        $mediatorId = intval($request->getQuery('mediatorId', 0));

        //检测批次解析和提交
        $where = $this->getWhere();

        if($mediationOrganId){
            array_push($where,"mediationOrganId = ".$mediationOrganId);
        }
        if($mediatorId){
            array_push($where,"mediatorId = ".$mediatorId);
        }
        $add_begin_end = trim($this->getRequest()->getQuery('add_begin_end', ''));
        if($add_begin_end){
            $query['add_begin_end'] = $add_begin_end;
            $date_tmp =  explode(" 到 ",$add_begin_end);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "addTime >= {$begin_date}");
            }
        }


        $query = [
            'mediationOrganId' => $mediationOrganId,
            'submitStatus' => $submitStatus,
            'add_begin_end' => $add_begin_end,
            'limit' => $limit,
        ];

        $page = $page ? $page : 1;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => ($page - 1) * $limit,
            'order' => 'id DESC'
        );

        $arrList = Module_Mediate_BashHandel::getInstance()->getAllBySearch([],$seacher,true);
        $total = Module_Mediate_BashHandel::getInstance()->getAllBySearch(["count(*) as num"], ['where' => $where], true);
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        $this->getMediator();

        SmartyAdapter::assign('arrList', $arrList);
        SmartyAdapter::assign('disputeType',  Module_Mediate_Case::$disputeType);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));
    }


    //导入案件
    public function uploadreallocateAction()
    {
        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);
            if(!empty($data['assetsId'])){
                $assetsId = $data['assetsId'];
                $assets = Module_InfoBase_Assets::getInstance()->getItemById($assetsId,true);
                if(empty($assets)){
                    AjaxTool::returnJsonData(403,'找到不到对应的资产方');
                }
            }
            if(empty($data['importRecordId']) && empty($data['assetsId'])){
                AjaxTool::returnJsonData(403,'导入批次id或资产方必须有其中之一');
            }
            if(empty($data['contentType'])){
                AjaxTool::returnJsonData(403,'请选择表数据内容');
            }
            $file = $this->getRequest()->getFiles('file');
            if ($file['error'] == 4) {
                AjaxTool::returnJsonData(404,'请上传文件');
            }
            $img_url = '';
            if ($file['error'] != 4) {
                $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'uploadreallocate');
                if (!$uploadFile || $uploadFile['code']) {
                    AjaxTool::returnJsonData(405,'上传失败');
                }
                $img_url = $uploadFile['data'];
            }
            $file_path=  '/resource' . $img_url;
            $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
            $file_info = pathinfo($url);
            if ($file_info && strtolower($file_info['extension']) == 'csv') {
                $res = array_map('str_getcsv', file($url));
                if ($res) {
                    unset($res[0]);
                }
            } else {
                try {
                    $res = Lib_XlsxRead::getInstance()->execute($url,1);
                } catch (Exception $e) {
                    AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                }
                if (empty($res)) {
                    AjaxTool::returnJsonData(407,'未发现数据');
                }
            }
            $header = $res[1];
            unset($res[1]);
            if (!$res) {
                AjaxTool::returnJsonData(408, "未发现数据");
            }
            if(empty($header)){
                AjaxTool::returnJsonData(409, "未发现表格表头");
            }
            //先生成批次,然后再进行检查
            $entry_record_insert = [
                'assetsId'=> empty($data['assetsId']) ? 0 : $data['assetsId'],
                'importRecordId'=> empty($data['importRecordId']) ? 0 : $data['importRecordId'],
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',
                'mediatorId'=> $this->admin['id'],
                'mediatorName'=> $this->admin['name'],
                'submitStatus'=>1,//1未提交 2提交中 3提交完成
                'addTime'=>time(),
                'updateTime'=>time(),
                'handelType'=>2,
                'upload_num'=>count($res),
                'handelWhere'=>json_encode(['contentType'=>$data['contentType']]),
                'filePath'=>$file_path,//上传文件地址
            ];

            $recordId = Module_Mediate_BashHandel::getInstance()->singleInsert($entry_record_insert);
            if(!$recordId){
                AjaxTool::returnJsonData(500, "入库失败");
            }
            AjaxTool::returnJsonData(200, "导入成功");

        }

    }
    //导入案件
    public function uploadWithdrawAction()
    {
        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);

            if(!empty($data['assetsId'])){
                $assetsId = $data['assetsId'];
                $assets = Module_InfoBase_Assets::getInstance()->getItemById($assetsId,true);
                if(empty($assets)){
                    AjaxTool::returnJsonData(403,'找到不到对应的资产方');
                }
            }
            if(empty($data['importRecordId']) && empty($data['assetsId'])){
                AjaxTool::returnJsonData(403,'导入批次id或资产方必须有其中之一');
            }
            if(empty($data['fileType'])){
                AjaxTool::returnJsonData(403,'请选择处理类型');
            }
            if(empty($data['contentType'])){
                AjaxTool::returnJsonData(403,'请选择表数据内容');
            }
            $file = $this->getRequest()->getFiles('file');
            if ($file['error'] == 4) {
                AjaxTool::returnJsonData(404,'请上传文件');
            }
            $img_url = '';
            if ($file['error'] != 4) {
                $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'uploadwithdraw');
                if (!$uploadFile || $uploadFile['code']) {
                    AjaxTool::returnJsonData(405,'上传失败');
                }
                $img_url = $uploadFile['data'];
            }
            $file_path=  '/resource' . $img_url;
            $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
            $file_info = pathinfo($url);
            if ($file_info && strtolower($file_info['extension']) == 'csv') {
                $res = array_map('str_getcsv', file($url));
                if ($res) {
                    unset($res[0]);
                }
            } else {
                try {
                    $res = Lib_XlsxRead::getInstance()->execute($url,1);
                } catch (Exception $e) {
                    AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                }
                if (empty($res)) {
                    AjaxTool::returnJsonData(407,'未发现数据');
                }
            }
            $header = $res[1];
            unset($res[1]);
            if (!$res) {
                AjaxTool::returnJsonData(408, "未发现数据");
            }
            if(empty($header)){
                 AjaxTool::returnJsonData(409, "未发现表格表头");
            }
            //先生成批次,然后再进行检查
            $entry_record_insert = [
                'assetsId'=> empty($data['assetsId']) ? 0 : $data['assetsId'],
                'importRecordId'=> empty($data['importRecordId']) ? 0 : $data['importRecordId'],
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',
                'mediatorId'=> $this->admin['id'],
                'mediatorName'=> $this->admin['name'],
                'submitStatus'=>1,//1未提交 2提交中 3提交完成
                'addTime'=>time(),
                'updateTime'=>time(),
                'handelType'=>1,
                'upload_num'=>count($res),
                'handelWhere'=>json_encode(['contentType'=>$data['contentType'],'fileType'=>$data['fileType']]),
                'filePath'=>$file_path,//上传文件地址
            ];

            $recordId = Module_Mediate_BashHandel::getInstance()->singleInsert($entry_record_insert);
            if(!$recordId){
                AjaxTool::returnJsonData(500, "入库失败");
            }
            AjaxTool::returnJsonData(200, "导入成功");

        }

    }


    //下载文件模板
    public function downTemplateAction()
    {
        $request = $this->getRequest();
        $type = intval($request->getQuery('type', 1));
        if($type == 1){
            $paramList = [
                [
                    1 => 'TJ120012011',
                ],
                [
                    1 => 'TJ120012012',

                ],
                [
                    1 => 'TJ120012013',

                ],
                [
                    1 => 'TJ120012014',

                ],
            ];
            Lib_XlsxExport::getInstance()->downExcel($paramList, ["身份证号/合同号/案件标识号"],'撤案导入模板');
            exit;
        }else{
            $paramList = [
                [
                    1 => 'TJ120012011',
                    2 => '张三',
                ],
                [
                    1 => 'TJ120012012',
                    2 => '张三',
                ],
                [
                    1 => 'TJ120012013',
                    2 => '李四',
                ],
                [
                    1 => 'TJ120012014',
                    2 => '李四',

                ],
            ];
            Lib_XlsxExport::getInstance()->downExcel($paramList, ["身份证号/合同号/案件标识号",'调解员名字'],'撤案导入模板');
            exit;
        }

    }

    //提交批次
    public function submitRecordAction(){
        $recordId = $this->getRequest()->getPost('recordId', '');
        if(empty($recordId)){
            AjaxTool::returnJsonData(400, "参数异常");
        }
        //案件批次提交
        $record = Module_Mediate_BashHandel::getInstance()->getOne(['id'],['submitStatus=1',"id = {$recordId}"]);
        if(empty($record)){
            AjaxTool::returnJsonData(200, '改数据不存在或已提交');
        }
        //更新批次为提交中
        $res = Module_Mediate_BashHandel::getInstance()->singleUpdate(["id"=>$recordId,"submitStatus"=>2]);
       if(!$res){
           AjaxTool::returnJsonData(400, '数据库更新失败');
       }
        AjaxTool::returnJsonData(200, '提交成功');
    }
    //提交批次
    public function deleteRecordAction(){
        $recordId = $this->getRequest()->getPost('recordId', '');
        if(empty($recordId)){
            AjaxTool::returnJsonData(400, "参数异常");
        }
        //案件批次提交
        $record = Module_Mediate_BashHandel::getInstance()->getOne(['id'],['submitStatus=1',"id = {$recordId}"]);
        if(empty($record)){
            AjaxTool::returnJsonData(200, '改数据不存在或已提交不允许删除');
        }
        //更新批次为提交中
        $res = Module_Mediate_BashHandel::getInstance()->deleteItemById($recordId);
        if(!$res){
            AjaxTool::returnJsonData(400, '数据库更新失败');
        }
        AjaxTool::returnJsonData(200, '提交成功');
    }
}
